<template>
	<div ref="chartRef" class="w-full h-full"></div>
</template>

<script setup lang="ts" name="lineChart">
import { tryOnUnmounted, useDebounceFn } from '@vueuse/core';
import * as echarts from 'echarts';
import { useEventListener } from '/@/hooks/event/useEventListener';
const props = defineProps({
	encodeY: {
		type: Number,
		default: 1,
	},
	data: {
		type: Array,
		default: () => [],
	},
});
const chartRef = ref();
let resizeFnPollute = resize;
let removeResizeFn = () => {};
let instance: any;
resizeFnPollute = useDebounceFn(resize, 200);
watch(
	() => props.data,
	(val) => {
		setOptions();
	},
	{
		deep: true,
	}
);
const options = {
	grid: { left: '10', bottom: '10', right: '10', top: '30', containLabel: true },
	tooltip: {
		trigger: 'axis',
	},
	toolbox: {
		feature: {
			saveAsImage: {},
		},
	},
	legend: { show: true },
	xAxis: {
		show: true,
		type: 'category',
		axisLabel: { show: true, color: '#9b9c9c' },
		axisLine: { show: true, lineStyle: { color: '#9b9c9c', type: 'dotted' } },
		axisTick: { show: true, alignWithLabel: true },
		splitLine: { show: true, interval: 1, lineStyle: { color: '#eeeeee', type: 'dashed' } },
	},
	yAxis: {
		show: true,
		type: 'value',
		axisLabel: { show: true, showMinLabel: false, showMaxLabel: false, color: '#9b9c9c' },
		axisLine: { show: true, lineStyle: { color: '#9b9c9c', type: 'dotted' } },
		axisTick: { show: false },
		splitLine: { show: true, lineStyle: { color: '#eeeeee', type: 'dashed' } },
		min: function (v) {
			return (v.min * 0.8).toFixed(2);
		},
		max: function (v) {
			return (v.max * 1.2).toFixed(2);
		},
	},
	series: [],
};
const setOptions = () => {
	const series: any = props.data.map((item: any) => {
		return {
			data: item.data,
			name: item.name,
			encode: { x: 'RecordTime', y: props.encodeY },
			connectNulls: false,
			type: 'line',
			smooth: true,
			symbol: 'circle',
			symbolSize: [12, 12],
			showSymbol: false,
			lineStyle: { width: 2 },
		};
	});
	if (!instance) {
		instance = echarts.init(chartRef.value);
		const { removeEvent } = useEventListener({
			el: window,
			name: 'resize',
			listener: resizeFnPollute,
		});
		removeResizeFn = removeEvent;

		options.series = series;
		instance.setOption(options);
		return;
	}
	instance.setOption({ series });
};
function resize() {
	const config = {
		animation: {
			duration: 300,
			easing: 'quadraticIn',
		},
	};
	instance.resize(config);
}
onMounted(() => {
	setTimeout(() => {
		setOptions();
		nextTick(() => {
			resize();
		});
	}, 200);
});

tryOnUnmounted(() => {
	removeResizeFn();
});
</script>
